package com.hmdp.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.common.constant.RedisConstants;
import com.hmdp.common.constant.SystemConstants;
import com.hmdp.core.service.IBlogService;
import com.hmdp.core.service.IFollowService;
import com.hmdp.core.service.IUserService;
import com.hmdp.entity.db.Blog;
import com.hmdp.core.mapper.BlogMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.entity.db.Follow;
import com.hmdp.entity.db.User;
import com.hmdp.entity.dto.Result;
import com.hmdp.entity.dto.ScrollResult;
import com.hmdp.entity.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private IFollowService followService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void initFeed() {
        log.info("初始化feed收件箱缓存start");

        // 1. 获取所有blog并按照作者分组
        List<Blog> blogList = this.list(new LambdaQueryWrapper<>(null));
        if(blogList.isEmpty()) {
            log.info("初始化feed收件箱缓存end");
            return;
        }
        Map<Long, List<Blog>> blogMap = blogList.stream().collect(Collectors.groupingBy(Blog::getUserId));

        // 2. 获取用户的所有关注者
        List<Follow> followList = followService.list(new LambdaQueryWrapper<>(null));
        if(followList.isEmpty()) {
            log.info("初始化feed收件箱缓存end");
            return;
        }
        Map<Long, List<Follow>> followMap = followList.stream().collect(Collectors.groupingBy(Follow::getUserId));

        // 3. 获取他的关注者的所有blog并添加到自己的邮箱
        followMap.forEach((k,v) -> {
            String key = RedisConstants.FEED_KEY + k;
            stringRedisTemplate.delete(key);
            v.forEach(f -> {
                List<Blog> blogs = blogMap.get(f.getFollowUserId());
                if(blogs.isEmpty()) {
                    return;
                }
                stringRedisTemplate.opsForZSet().add(
                        key,
                        blogs.stream().map(
                                m -> new DefaultTypedTuple<String>(
                                        m.getId().toString(),
                                        (double) m.getCreateTime().toInstant(ZoneOffset.ofHours(8)).toEpochMilli()
                                )
                        ).collect(Collectors.toSet())
                );
            });
        });
        log.info("初始化feed收件箱缓存end");
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if(blog == null) {
            return Result.fail("blog不存在");
        }
        queryBlogUser(blog);
        //查询blog是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null) {
            return;
        }
        Long uid = user.getId();
        //判断是否点赞过
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, uid.toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(f -> {
            queryBlogUser(f);
            isBlogLiked(f);
        });
        return Result.ok(records);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    @Override
    public Result likeBlog(Long id) {
        Long uid = UserHolder.getUser().getId();

        //判断是否点赞过
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, uid.toString());
        if(score == null) {
            boolean isSuccess = this.lambdaUpdate()
                    .setSql("liked = liked + 1")
                    .eq(Blog::getId, id)
                    .update();
            if(isSuccess) {
                stringRedisTemplate.opsForZSet().add(key,uid.toString(),System.currentTimeMillis());
            }
        } else {
            boolean isSuccess = this.lambdaUpdate()
                    .setSql("liked = liked - 1")
                    .eq(Blog::getId, id)
                    .update();
            if(isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key,uid.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        //查询top5的客户 0-4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        List<User> users = userService.lambdaQuery().in(User::getId,ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        List<UserDTO> userDTOS = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);

        if(isSuccess) {
            // 1. 查询作者的粉丝
            Long userId = user.getId();
            List<Follow> follows = followService.lambdaQuery()
                    .eq(Follow::getUserId,userId)
                    .list();
            for(Follow follow : follows) {
                // 2. 推送到粉丝的收件箱
                Long followUserId = follow.getFollowUserId();
                String key = RedisConstants.FEED_KEY + followUserId;
                stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
            }
        }

        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryFollowBlog(Long max, Integer offset) {
        // 1. 获取当前用户
        Long userId = UserHolder.getUser().getId();

        // 2. 查询收件箱 ZREVRANGEBYSCORE [key] [max] [min] LIMIT offset count
        String key = RedisConstants.FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if(typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }

        // 3. 解析收件箱 blogId,minTime(时间戳),offset
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for(ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            // 获取id
            ids.add(Long.valueOf(tuple.getValue()));
            // 获取分数(时间戳)
            long time = tuple.getScore().longValue();
            if(time == minTime) {
                os ++;
            } else {
                minTime = time;
                os = 1;
            }
        }

        // 4. 查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = this.lambdaQuery()
                .in(Blog::getId,ids)
                .last("ORDER BY FIELD(id," + idStr + ")")
                .list();
        blogs.forEach(f -> {
            queryBlogUser(f);
            isBlogLiked(f);
        });

        // 5. 封装返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
}
